package com.hoku.auth.dao;

import com.google.common.collect.Maps;
import com.hoku.auth.model.User;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Repository;

import javax.validation.Valid;
import java.util.Map;

/**
 * @author ZHUFEIFEI
 */
@Repository
public class UserDaoImpl implements IUserDao, InitializingBean {

    private Map<String, User> memory = Maps.newConcurrentMap();
    @Autowired
    private PasswordEncoder encoder;

    @Override
    public User findByUsername(String username) {
        return memory.get(username);
    }

    @Override
    public void save(@Valid User user) {
        memory.put(user.getUsername(), user);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        User user = new User();
        user.setUsername("admin");
        user.setPassword(this.encoder.encode("123456"));
        user.setAuthorities(AuthorityUtils.createAuthorityList("admin_role", "test_role"));
        user.setAccountNonExpired(true);
        user.setAccountNonLocked(true);
        user.setCredentialsNonExpired(true);
        user.setEnabled(true);
        this.memory.put("admin", user);
    }
}
